package com.cavas.domain.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.cavas.domain.bean.Cotisation;
import com.cavas.domain.bean.Membre;

@Repository
public class DaoCotisationImpl implements DaoCotisation{

	
	@Autowired
	SessionFactory sessionFactory;
	
	public void setSessionFactory(SessionFactory session){
		this.sessionFactory = session;
	}
	
	@Override
	public void addCotisation(Cotisation rt, int id_membre) {
		Session session = sessionFactory.getCurrentSession();
		Membre membre = (Membre) session.get(Membre.class, id_membre);
		rt.setMembre(membre);
		rt.setNom(membre.getNom());
		session.save(rt);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Cotisation> allCotisation() {
		return sessionFactory.getCurrentSession().createQuery("from Cotisation").list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Cotisation> getCotisationMembre(String mail) {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from Cotisation clt where clt.nom = :nome");
		query.setParameter("nome", mail);
		return  query.list();
	}

	@Override
	public void deleteCotisation(int id) {
		Session session = sessionFactory.getCurrentSession();
		Cotisation rt = (Cotisation) session.get(Cotisation.class, id);
		if(rt != null)
			session.delete(rt);
		
	}

	@Override
	public int TotalCotisation() {
		List<Cotisation> list = this.allCotisation();
		int total = 0;
		
		for(Cotisation r : list){
			total = total + r.getMontant();
		}
		return total;
	}
}
